package edu.gatech.cs2340.teamrocket.control.networking.dialog;

import java.io.IOException;
import java.net.Socket;
import edu.gatech.cs2340.teamrocket.control.networking.node.Server;
import edu.gatech.cs2340.teamrocket.control.networking.message.LoginFailureMessage;
import edu.gatech.cs2340.teamrocket.control.networking.message.LoginMessage;
import edu.gatech.cs2340.teamrocket.control.networking.message.LoginSuccessMessage;
import edu.gatech.cs2340.teamrocket.control.networking.message.Message;
import edu.gatech.cs2340.teamrocket.control.networking.message.TimeoutMessage;

/**
 * A Server's Dialog. Will add itself to the Server's list of active Dialogs
 * when it receives a correct LoginMessage.
 *
 * @author Joe Tacheron
 */
public class ServerDialog extends Dialog {

    // waiting for user credentials
    private volatile boolean waiting;
    private boolean loggedIn;
    private String username;
    private String password;

    public ServerDialog(Server server, Socket socket) throws IOException {
        super(server, socket);
    }

    @Override
    public void start(){
        super.start();

        waiting = true;

        // timeout
        new Thread(new Runnable(){
            @Override
            public void run(){
                try{
                    Thread.sleep(5000);
                }
                catch(InterruptedException e) { }
                ServerDialog.this.waiting = false;
                synchronized(ServerDialog.this){
                    ServerDialog.this.notify();
                }
            }
        }).start();

        while(waiting)
            try {
                synchronized(ServerDialog.this){
                    wait();
                }
            }
            catch (InterruptedException ignore) { }

        if(!loggedIn){
            this.send(new TimeoutMessage(0)); // TODO: uses int literal
            this.close();
        }
    }

    @Override
    public void handle(Message m){
        if(loggedIn)
            super.handle(m);
        else if(m instanceof LoginMessage){
            try{
                username = (String)m.get(0);
                password = (String)m.get(1);

                if(!password.equals(((Server)endpoint).getPassword()))
                    throw new RuntimeException();
                else{
                    waiting = false;
                    loggedIn = true;
                    synchronized(this){
                        notify();
                    }
                }
            }
            catch(RuntimeException e){
                this.send(new LoginFailureMessage(m.getMessageID()));
                this.close();
            }

            ((Server)endpoint).addNewDialog(this);
            this.send(new LoginSuccessMessage(m.getMessageID()));
        }
    }

    public String username(){
        return username;
    }
}
